import datetime
import urllib.request
import traceback
import string

from bs4 import BeautifulSoup
import jieba
import jieba.analyse

# from sqlalchemy import Column, Integer, ForeignKey, String, create_engine, or_, Text, DateTime, Date, Time, text
# from sqlalchemy.orm import relationship, sessionmaker
# from sqlalchemy.ext.declarative import declarative_base
from PIL import ImageGrab

# engine = create_engine("sqlite:///app.db", echo=True)
# Base = declarative_base(bind=engine)
# Session = sessionmaker(bind=engine)
# session = Session()

from flask import Flask,jsonify, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)


class OrderDetail(db.Model):
    __tablename__ = 'order_detail'
    id = db.Column(db.Integer, primary_key=True)
    # parent_id = Column(Integer, ForeignKey('node.id'))
    xuhao = db.Column(db.String(50), comment='序号')
    orderType = db.Column(db.String(200), comment='订单类型')
    number = db.Column(db.String(500), comment='编号')
    name = db.Column(db.String(500), comment='名称')
    description = db.Column(db.Text(), comment='描述')
    company = db.Column(db.String(200), comment='客户')
    address = db.Column(db.String(500), comment='地址')
    dateFrom = db.Column(db.Date(), comment='开始')
    dateFrom_time = db.Column(db.Time(), comment='开始time')
    dateTo = db.Column(db.Date(), comment='结束')
    dateTo_time = db.Column(db.Time(), comment='结束time')
    deadline = db.Column(db.Date(), comment='截止日期')
    deadline_time = db.Column(db.Time(), comment='截止日期time')
    product = db.Column(db.String(200), comment='产品')
    defaultTechnology = db.Column(db.String(200), comment='默认工艺')
    technology = db.Column(db.String(200), comment='已选定')
    productionLine = db.Column(db.String(200), comment='生产线')
    plannedQuantity = db.Column(db.Integer, comment='计划数量')
    plannedQuantityForAdditionalUnit = db.Column(db.Integer, comment='计划数量（附加单位）')
    doneQuantity = db.Column(db.Integer, comment='完成数量')
    orderCategory = db.Column(db.String(200), comment='订单类型:无，接受订单，订单发货，订单生产中，订单结束')
    division = db.Column(db.String(200), comment='部门')
    addtime = db.Column(db.DateTime, default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), comment='添加时间')
    # children = relationship("Node",
    #                 lazy="joined",
    #                 join_depth=10)

class Order(db.Model):
    __tablename__ = 'order'
    id = db.Column(db.Integer, primary_key=True)
    xuhao = db.Column(db.String(50), comment='序号')
    number = db.Column(db.String(500), comment='编号')
    name = db.Column(db.String(500), comment='名称')
    state = db.Column(db.String(200), comment='状态')
    deadline = db.Column(db.String(200), comment='截止日期')
    technologyNumber = db.Column(db.String(200), comment='工艺编号')
    productNumber = db.Column(db.String(500), comment='产品编号')
    plannedQuantity = db.Column(db.Integer, comment='计划数量')
    unit = db.Column(db.String(200), comment='单位')
    plannedQuantityForAdditionalUnit = db.Column(db.Integer, comment='附加单位计划数量')
    unitForAdditionalUnit = db.Column(db.Integer, comment='附加单位')
    companyName = db.Column(db.Integer, comment='客户')
    orderCategory = db.Column(db.String(200), comment='订单类型:无，接受订单，订单发货，订单生产中，订单结束')
    masterOrderNumber = db.Column(db.String(200), comment='主订单')
    masterOrderDefinitionNumber = db.Column( db.String( 200 ), comment = '主订单定义')
    workPlanDelivered = db.Column( db.String( 200 ), comment = '交付工作计划')
    divisionName = db.Column( db.String( 200 ), comment = '部门')
    isSubcontracted = db.Column( db.String( 200 ), comment = '分包商')
    annotation = db.Column( db.String( 200 ), comment = '批注')
    existsRepairOrders = db.Column( db.String( 200 ), comment = '修复订单')
    addtime = db.Column(db.String(200), default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), comment='添加时间')
    # 0 未写入，1 已经写入
    iswrite = db.Column( db.Integer, default = db.text( '0' ), comment = '是否写入' )
    def to_dict(self):
        dict = self.__dict__
        # dict['addtime'] = dict['addtime'].strftime("%Y-%m-%d %H:%M:%S")
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict

db.create_all()



# result = session.query(Order).order_by(Order.id.desc()).all()




@app.route( '/' )  # 添加路由：根
def index():
    return redirect(url_for('items'),code=302)

@app.route( '/orderlist' )  # 添加路由：根
def orderlist():
    result = db.session.query(Order).order_by(Order.id.desc()).all()
    result = [i.to_dict() for i in result]
    res = {}
    res['code'] = 1
    res['msg'] = 'success'
    res['data'] = result
    return jsonify(res)

@app.route('/edit/<id>/iswrite/<iswrite>')
def edit(id,iswrite):
    res_first = db.session.query( Order ).filter( Order.id == id ).first()
    postdata = request.form
    if res_first:
        if 'iswrite' in postdata.keys():
            iswrite = postdata['iswrite']
        res_first.iswrite = iswrite if iswrite else 1
        db.session.commit()
    return redirect( url_for( 'items' ), code = 302 )
    # result = db.session.query(Order).filter( Order.id == id ).first()
    # result = result.to_dict()
    # res = {}
    # res['code'] = 1
    # res['msg'] = 'success'
    # res['data'] = result
    # return jsonify( res )

@app.route('/add')
def add():
    name = "准备添加吧！！！"
    return render_template('add.html', name=name)

@app.route('/items')
def items():
    list_columns = ['id','xuhao', 'number', 'name', 'state', 'deadline', 'technologyNumber', 'productNumber',
                    'plannedQuantity', 'unit', 'plannedQuantityForAdditionalUnit',
                    'unitForAdditionalUnit', 'companyName', 'orderCategory',
                    'masterOrderNumber', 'masterOrderDefinitionNumber',
                    'workPlanDelivered', 'divisionName', 'isSubcontracted', 'annotation', 'existsRepairOrders','iswrite','addtime']
    result = db.session.query(Order).order_by(Order.id.desc()).all()
    result = [i.to_dict() for i in result]
    return render_template('items.html', items=result, list_columns=list_columns)


@app.route('/adddata', methods=['POST'])
def adddata():
    postdata = request.form
    recognize_info = {'postdata': postdata}
    return jsonify(recognize_info)


if __name__ == '__main__':
    app.run( debug = True )